package emailx

import (
	"crypto/tls"
	"fmt"
	"net/smtp"

	"ginx/internal/global/configs"
)

var E *Emailx

type Emailx struct {
	senderEmail string
	authCode    string
	smtpServer  string
	smtpPort    int
}

func New() *Emailx {
	return &Emailx{}
}

// NewEmailClient 创建一个新的邮件客户端实例
func (m *Emailx) NewEmail(c *configs.Config) *Emailx {
	return &Emailx{
		senderEmail: c.Email.SenderEmail,
		authCode:    c.Email.AuthCode,
		smtpServer:  c.Email.SmtpServer,
		smtpPort:    c.Email.SmtpPort,
	}
}

// SendEmail 定义发送邮件的函数
func (m *Emailx) SendEmail(to []string, subject, body string) error {
	// 构建邮件消息
	message := fmt.Sprintf("From: %s\r\n", m.senderEmail)
	message += fmt.Sprintf("To: %s\r\n", to[0])
	message += fmt.Sprintf("Subject: %s\r\n", subject)
	message += "MIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n"
	message += body

	// 配置 TLS 连接
	tlsConfig := &tls.Config{
		InsecureSkipVerify: true,
		ServerName:         m.smtpServer,
	}

	// 连接到 SMTP 服务器
	conn, err := tls.Dial("tcp", fmt.Sprintf("%s:%d", m.smtpServer, m.smtpPort), tlsConfig)
	if err != nil {
		return err
	}
	defer conn.Close()

	// 创建 SMTP 客户端
	client, err := smtp.NewClient(conn, m.smtpServer)
	if err != nil {
		return err
	}
	defer client.Quit()

	// 进行认证
	auth := smtp.PlainAuth("", m.senderEmail, m.authCode, m.smtpServer)
	if err = client.Auth(auth); err != nil {
		return err
	}

	// 设置发件人和收件人
	if err = client.Mail(m.senderEmail); err != nil {
		return err
	}
	for _, addr := range to {
		if err = client.Rcpt(addr); err != nil {
			return err
		}
	}

	// 发送邮件数据
	writer, err := client.Data()
	if err != nil {
		return err
	}
	_, err = writer.Write([]byte(message))
	if err != nil {
		return err
	}
	err = writer.Close()
	if err != nil {
		return err
	}

	return nil
}

func init() {
	E = New().NewEmail(configs.C)
}
